from ftplib import FTP
from tqdm import tqdm
import os

# FTP服务器的连接信息

def upgt(new_name):
    ftp_host = "198.12.127.45"
    ftp_user = "administrator"
    ftp_password = "WgAJGfFCe2kZwun"
    ftp_port = 21  # 将端口设置为22

    # 本地文件路径和文件名
    local_file_path=f'dist/{new_name}'
    # 远程FTP服务器上的文件路径和文件名
    remote_file_path = f"/{new_name}"

    try:
        # 创建FTP连接
        ftp = FTP()
        ftp.connect(ftp_host, ftp_port)
        ftp.login(ftp_user, ftp_password)

        # 打开本地文件并上传到FTP服务器
        with open(local_file_path, 'rb') as local_file:
            file_size = len(local_file.read())
            local_file.seek(0)
            with tqdm(total=file_size, unit='B', unit_scale=True, unit_divisor=1024) as pbar:
                def progress_callback(data):
                    pbar.update(len(data))
                ftp.storbinary(f'STOR {remote_file_path}', local_file, 1024, callback=progress_callback)

        print(f"文件 '{local_file_path}' 已上传到 '{remote_file_path}' on FTP server.")
    except Exception as e:
        print(f"发生错误: {str(e)}")
    finally:
        if ftp:
            ftp.quit()

def downloadImg(ftp, remote_directory, local_directory):

    try:
        os.makedirs(local_directory)  # 创建本地目录
    except OSError:
        pass

    ftp.cwd(remote_directory)  # 进入远程目录

    remote_files = ftp.nlst()  # 列出远程目录中的文件和子目录

    for remote_file in remote_files:
        local_file = os.path.join(local_directory, remote_file)
        with open(local_file, 'wb') as file:
            # 使用 tqdm 显示下载进度
            with tqdm(total=ftp.size(remote_file), unit='B', unit_scale=True, unit_divisor=1024) as pbar:
                ftp.retrbinary('RETR ' + remote_file, lambda data: (file.write(data), pbar.update(len(data))))

    ftp.cwd('..')  # 返回上一级目录
